<template>
  <b-page class="fsgl-list">
    <a-alert
      v-if="isExportLoading"
      message="提示"
      description="公众号粉丝同步中，预计需要5-20分钟，请稍后查看！"
      type="success"
      show-icon
    />
    <div class="filter-container d-jcs-aic">
      <div class="d-aic">
        <span class="flex-fixed">当前公众号：</span>
        <a-select
          class="filter-item ml-10"
          placeholder="公众号"
          :value="mpId"
          style="height: 32px;width:100px"
          @change="mpChange">
          <a-select-option
            v-for="item in mpList"
            :key="item.value"
          >{{ item.label }}
          </a-select-option>
        </a-select>
        <a-input
          class="ml-10"
          allowClear
          v-model="nickname"
          placeholder="请输入昵称,备注名进行搜索"
          style="width: 300px;"
          @change="getPage"/>
      </div>
      <a-button style="width:120px" type="primary" @click="fixFan" :loading="isExportLoading">同步</a-button>
    </div>
    <div class="d-jce-aic">
      <div class="update-desc-state d-jcc-aic" v-if="isExportLoading">
        <div style="height: 20px"> 正在从公众号导入，请等待...</div>
        <div class="material-icons desc-state-icon">autorenew</div>
      </div>
    </div>
    <div class="fsgl-list-content">
      <div class="fsgl-list-content-left">
        <div class="current-fan-tag">全部粉丝</div>
        <div style="display: flex;flex-direction:column;justify-content: space-around;">
          <div v-if="fanList.length>0" style="min-height:500px">
            <div
              v-for="(item,index) in fanList"
              :key="index"
              style="padding: 12px 0;border-bottom: 1px solid #f0f0f0!important;">
              <div style="display: flex;justify-content: space-between">
                <div style="display: flex">
                  <div class="fsgl-list-content-left-img">
                    <img style="width: 50px;height: 50px;" :src="item.headImgUrl">
                  </div>
                  <div style="display: flex;flex-direction: column;justify-content: space-between">
                    <div style="font-weight: bold;font-size: 14px;color: #232735">
                      {{ item.remark?item.remark+'('+item.nickname+')':item.nickname }}
                      <a-popover
                        :title="null"
                        trigger="click"
                        placement="right"
                        v-model="item.fanRemarkDialog"
                        width="400">
                        <template slot="content">
                          <a-input
                            v-model="fanRemark"
                            type="text"
                            :show-word-limit="true"
                            placeholder="备注名"
                            :maxLength="16"/>
                          <div style="display: flex;justify-content: flex-end;margin-top: 20px">
                            <!--                            <a-button @click="item.fanRemarkDialog=false">-->
                            <!--                              取消-->
                            <!--                            </a-button>-->
                            <a-button type="primary" @click="saveFanRemark(item)">
                              确定
                            </a-button>
                          </div>
                        </template>
                        <a-icon
                          type="edit"
                          @click="initRemark(item)"
                          class="edit-fan-name"/>
                      </a-popover>
                    </div>
                    <div style="display:flex;margin-top: 10px">
                      <div><img
                             v-if="item.sex===2"
                             style="width: 20px;height: 20px"
                             src="../../assets/woman.png"/>
                        <img
                          v-else
                          style="width: 17px;height: 17px"
                          src="../../assets/man.png"/></div>
                      <div style="margin-left: 5px;font-size: 12px;color: rgba(0,0,0,.45);line-height: 18px">
                        {{ item.province }}{{ item.city }}
                      </div>
                    </div>
                  </div>
                </div>
                <div style="display: flex">
                  <div>
                    <a-tag
                      style="margin: 0 10px 10px 0;"
                      v-for="(tagShow, j) in getShowTag(item.tagList)"
                      :key="j">
                      {{ tagShow }}
                    </a-tag>
                  </div>
                  <div style="margin-left: 20px">
                    <a-popover
                      placement="left"
                      trigger="click"
                      v-model="item.fanTagDialog"
                      width="400">
                      <template slot="content">
                        <div style="width: 100%;height: 100%;padding: 12px 16px">
                          <div style="display: flex;flex-wrap: wrap;width: 300px;padding-left: 22px">
                            <a-tag
                              style="margin: 0 10px 10px 0;cursor: pointer"
                              v-for="(tag,i) in tempTagList"
                              :key="i"
                              @click="switchActive(tag,i)"
                              :color="getTagActive(tag)">
                              {{ tag.name }}
                            </a-tag>
                          </div>
                          <div style="display: flex;justify-content: flex-end;margin-top: 20px">
                            <a-button type="primary" @click="saveFanTag(item,index)">
                              确定
                            </a-button>
                          </div>
                        </div>
                      </template>
                      <b-button
                        suffix-icon="down"
                        style="position: relative;cursor: pointer;"
                        type="default"
                        ghost="default"
                        btn-content="更改标签"
                        @click="getTagList(item.tagList)">
                      </b-button>
                    </a-popover>
                  </div>
                </div>

              </div>

            </div>
          </div>
          <div v-else class="fsgl-list-empty">暂无数据
          </div>
          <div class="mt-20 d-jce-aic">
            <a-pagination v-model="current" :total="total" show-less-items @change="changePage"/>
          </div>
        </div>

      </div>
      <div class=" fsgl-list-content-right">
        <div class="current-fan-tag" style="position: relative;display: flex;justify-content: space-between;">
          <div>粉丝标签</div>
          <div class="add-fan-tag" @click="addTagDialog=true">+&nbsp;新建标签</div>
          <a-card
            v-if="addTagDialog"
            style="position: absolute;bottom: -130px;left: 0;width: 100%;height: 130px;">
            <a-input v-model="addTagName" type="text" :show-word-limit="true" :maxLength="16"/>
            <div style="display: flex;justify-content: flex-end;margin-top: 20px">
              <a-button @click="addTagDialog=false">
                取消
              </a-button>
              <a-button class="ml-10" type="primary" @click="saveTag">
                确定
              </a-button>
            </div>
          </a-card>
        </div>

        <div class="fsgl-list-content-right-title" :class="{'active':tagId===0}" @click="getTagFan()">
          <div>全部粉丝</div>
          <div>{{ totalFan }}人</div>
        </div>
        <div
          class="fsgl-list-content-right-title"
          v-for="(item,index) in tagList"
          :key="index"
          :class="{'active':activeTagId===item.id}"
          @click="getTagFan(item)">
          <div style="color: #232735">{{ item.name }}</div>
          <div class="fan-tag-right">{{ item.count }}人
            <a-icon
              class="tag-edit-btn"
              type="edit"
              @click.stop="updateTag(item)"/>
            <a-icon
              type="close"
              class="tag-edit-btn"
              @click.stop="deleteTag(item)"/>
          </div>
        </div>
      </div>
    </div>
  </b-page>
</template>

<script>
    import TAG from '../../../api/mp/MpFollowerController'
    import API from '../../../api/mp/mp'
    import BButton from '../../components/b-button'

    export default {
        name: 'FsglList',
        components: { BButton },
        data () {
            return {
                isExportLoading: false,
                size: 10,
                current: 0,
                mpList: [],
                mpId: null,
                nickname: null,
                tagId: null,
                fanList: [],
                total: 0,
                tagList: [],
                tempTagList: [],
                activeTagId: 0,
                editTagId: null,
                addTagName: '',
                fanRemark: '',
                totalFan: 0,
                addTagDialog: false
            }
        },
        computed: {
            gzhUserId () {
                return this.$store.state.user.info.gzhUserId
            }
        },
        watch: {
            mpId () {
                this.initTag()
                this.getPage()
            },
            nickname () {
                this.getPage()
            },
            tagId () {
                this.getPage()
            }
        },
        mounted () {
            this.initSelector()
            this.checkRunningTask()
        },
        methods: {
            checkRunningTask () {
                TAG.checkRunningSync({ gzhUserId: this.gzhUserId }).then(res => {
                    if (this.isExportLoading && !res.synchronizing) {
                        this.$message.success(`导入完成`)
                        this.isExportLoading = false
                        this.getPage()
                    }
                    if (res.synchronizing) {
                        this.isExportLoading = true
                        setTimeout(() => {
                            this.checkRunningTask()
                        }, res.remaining + 2000)
                    }
                })
            },
            fixFan () {
                if (!this.mpId) {
                    this.$message.warning('还没有绑定公众号，不可同步哦')
                    return
                }
                if (this.isExportLoading) {
                    this.$message.warning(`正在导入，请等待。。。`)
                    return
                }
                TAG.tongbuFans(this.mpId, this.gzhUserId).then(res => {
                    this.isExportLoading = true
                    this.$message.warning(`正在同步，请等待。。。`)
                    setTimeout(() => {
                        this.checkRunningTask()
                    }, 5000)
                })
            },
            /**
             * 公众号选择器
             */
            mpChange (data) {
                this.mpId = data
            },
            getShowTag (tagList) {
                const list = []
                tagList.forEach(item => {
                    list.push(item.name)
                })
                return list
            },
            saveFanTag (fan, index) {
                const tagList = []
                this.tempTagList.forEach(item => {
                    if (item.active === 1) {
                        tagList.push(item.id)
                    }
                })
                TAG.addFansTag(this.gzhUserId, fan.id, fan.mpId, tagList).then(res => {
                    this.getPage()
                    this.initTag()
                    this.$message.success('保存成功')
                })
            },
            getTagActive (item) {
                if (item.active === 0) {
                    return ''
                } else {
                    return 'blue'
                }
            },
            switchActive (item, index) {
                if (item.active === 0) {
                    item.active = 1
                } else {
                    item.active = 0
                }
                this.tempTagList.splice(index, 1, item)
            },
            getTagList (fanTagList) {
                this.tempTagList = this.tagList
                this.tempTagList.forEach(item => {
                    item.active = 0
                    fanTagList.forEach(fanTag => {
                        if (fanTag.id === item.id) {
                            item.active = 1
                        }
                    })
                })
            },
            initTag () {
                TAG.tagCount(this.mpId, this.gzhUserId).then(res => {
                    this.tagList = res
                })
            },
            initSelector () {
                // 初始化自己的公众号账户
                API.listByCurrentMpList()
                    .then(res => {
                        if (res.length === 0) {
                            return
                        }
                        res.forEach(item => {
                            this.mpList.push({ label: item.mpName, value: item.mpId })
                        })
                        if (this.mpList.length > 0) {
                            this.mpId = this.mpList[0].value
                        } else {
                            this.mpId = ''
                        }
                    })
            },
            changePage (current) {
                this.current = current
                this.getPage()
            },
            getPage () {
                TAG.pageFans({ current: this.current, size: this.size }, {
                    mpId: this.mpId,
                    nickname: this.nickname,
                    tagId: this.tagId,
                    gzhUserId: this.gzhUserId
                }).then(res => {
                    this.fanList = res.records
                    this.fanList.forEach(item => {
                        this.$set(item, 'fanRemarkDialog', false)
                        this.$set(item, 'fanTagDialog', false)
                    })
                    this.current = res.current
                    this.size = res.size
                    this.total = res.total
                    if (!this.nickname && !this.tagId) {
                        this.totalFan = res.total
                    }
                })
            },
            saveTag () {
                if (this.addTagName.trim().length === 0) {
                    this.$message.error('请填写标签名')
                    return
                }
                TAG.saveTag({
                    id: this.editTagId,
                    mpId: this.mpId,
                    name: this.addTagName,
                    gzhUserId: this.gzhUserId
                }).then(() => {
                    this.$message.success('保存成功')
                    this.addTagDialog = false
                    this.editTagId = null
                    this.addTagName = null
                    this.initTag()
                    this.getPage()
                }).catch(err => {
                    this.$message.error(err.response.data.message)
                })
            },
            getTagFan (item) {
                if (item) {
                    this.activeTagId = item.id
                    this.tagId = item.id
                } else {
                    this.activeTagId = 0
                    this.tagId = null
                }
            },
            updateTag (tag) {
                this.addTagDialog = true
                this.addTagName = tag.name
                this.editTagId = tag.id
            },
            deleteTag (tag) {
                this.$confirm({
                    title: '提示',
                    content: `此操作将永久删除标签【${tag.name}】, 是否继续?`,
                    iconType: 'check-circle',
                    onOk: () => {
                        TAG.deleteModel(tag.id, this.gzhUserId).then(res => {
                            this.$message.success('删除成功')
                            this.getPage()
                            this.initTag()
                        })
                    }
                })
            },
            initRemark (item) {
                this.fanRemark = item.remark
            },
            saveFanRemark (item) {
                TAG.addFansRemark(item.id, this.fanRemark, this.gzhUserId).then(res => {
                    this.$message.success('保存成功')
                    this.getPage()
                })
            }
        }
    }
</script>

<style lang="less">
    .fsgl-list {
        height: 100%;

        .update-desc-state {
            height: 30px;
            font-size: 12px;
            color: #52C41A;

            .desc-state-icon {
                margin-left: 8px;
                font-size: 20px;
                animation: syncAnimal 1.5s forwards infinite;
            }
        }

        .fsgl-list-empty {
            padding-top: 100px;
            min-height: 500px;
            flex-grow: 1;
            width: 100%;
            display: flex;
            justify-content: center;
            font-size: 14px;
            color: #909399;
        }

        .edit-fan-name {
            position: relative;
            padding-left: 6px;
            color: #c8cbd9;
            cursor: pointer;
        }

        .edit-fan-name:hover {
            color: #5cb6ff;
        }

        .filter-container {
            padding: 10px 16px;
            background: white;
            display: flex;
            justify-content: space-between;
        }

        .add-fan-tag {
            font-size: 14px;
            float: right;
            color: #0c8eff;
            cursor: pointer;
        }

        .fsgl-list-content {
            display: flex;
            margin-top: 15px;
            min-height: 700px;
            width: 100%;

            .fsgl-list-content-left {
                padding: 20px;
                min-width: 700px;
                min-height: 700px;
                width: 70%;
                background: white;

                .fsgl-list-content-left-img {
                    margin-right: 16px;
                }
            }

            .current-fan-tag {
                font-size: 16px;
                color: #232735;
                font-weight: 700;
                line-height: 40px;
                border-bottom: 1px solid #f0f0f0 !important;
            }

            .fsgl-list-content-right {
                margin-left: 15px;
                padding: 20px;
                min-width: 230px;
                flex-grow: 1;
                min-height: 300px;
                background: white;

                .fsgl-list-content-right-title {
                    padding: 0 10px;
                    display: flex;
                    justify-content: space-between;
                    height: 40px;
                    line-height: 40px;
                    cursor: pointer;
                    font-size: 14px;
                    color: #909298;

                    &.active {
                        background: #f5f6fa;
                        border-radius: 5px;
                    }
                }

                .fan-tag-right {
                    .tag-edit-btn {
                        margin-left: 6px;
                        opacity: 0;
                    }

                    .tag-edit-btn:hover {
                        color: #0c8eff;
                        cursor: pointer;
                    }
                }

            }

            .fsgl-list-content-right-title:hover {
                background: #f5f6fa;
                border-radius: 5px;

                .tag-edit-btn {
                    opacity: 1;
                }
            }
        }
    }
</style>
